package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.authenticator.AuthenticationCookie;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;

@WebServlet(name = "LogoutControllerServlet", urlPatterns = "/LogoutControllerServlet")
public class LogoutControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -5733572554133458021L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			Principal principal = request.getUserPrincipal();

			if (principal == null) {
				return;
			}

			User user = User.get(principal.getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (request.getParameter("removeCookie") != null) {
				AuthenticationCookie.removeCookies(request, response);
			}

			request.getSession().invalidate();

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			request.setAttribute("message", "You have been successfully logged out of " + Configuration.getInstance().getSiteName() + ".");
			response.setHeader("referer", null);
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}
